import axios from 'axios';

// 支持多个后端地址的负载均衡
const API_BASE_URLS = [
  'http://localhost:8080',
  'http://localhost:8081',
  'http://localhost:8082'
];

// 当前使用的 API 地址
let currentApiBaseUrl = API_BASE_URLS[0];

// 创建基础 axios 实例
const createApiInstance = (baseURL) => {
  return axios.create({
    baseURL: baseURL,
    timeout: 30000, // 大文件上传需要更长时间
    withCredentials: true,
    headers: {
      'Content-Type': 'application/json'
    }
  });
};

// 主 API 实例
const api = createApiInstance(currentApiBaseUrl);

// 文件上传专用实例（支持进度监控）
const createUploadInstance = (baseURL) => {
  return axios.create({
    baseURL: baseURL,
    timeout: 0, // 上传超时设置为0，由业务逻辑控制
    withCredentials: true,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      // 进度回调在具体请求中处理
    }
  });
};

const uploadApi = createUploadInstance(currentApiBaseUrl);

// 请求拦截器 - 为普通API添加CSRF Token
api.interceptors.request.use(
  config => {
    // 只从sessionStorage读取token，确保每个标签页独立会话
    const token = sessionStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    // 添加CSRF Token（从响应头或localStorage获取，CSRF token可以共享）
    const csrfToken = localStorage.getItem('csrfToken');
    if (csrfToken) {
      config.headers['X-CSRF-TOKEN'] = csrfToken;
    }
    
    console.log('发送请求:', config.method, config.url, config.data);
    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 为上传API也添加请求拦截器
uploadApi.interceptors.request.use(
  config => {
        // 只从sessionStorage读取token，确保每个标签页独立会话
        const token = sessionStorage.getItem('token');
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
    
    // 添加CSRF Token
    const csrfToken = localStorage.getItem('csrfToken');
    if (csrfToken) {
      config.headers['X-CSRF-TOKEN'] = csrfToken;
    }
    
    console.log('上传请求:', config.method, config.url);
    return config;
  },
  error => {
    console.error('上传请求错误:', error);
    return Promise.reject(error);
  }
);

// 为上传API添加响应拦截器，获取CSRF Token
uploadApi.interceptors.response.use(
  response => {
    // 从响应头获取CSRF Token并保存
    const csrfToken = response.headers['x-csrf-token'];
    if (csrfToken) {
      localStorage.setItem('csrfToken', csrfToken);
    }
    
    const responseData = response.data;
    
    // 检查响应数据中的code字段，如果不是200，抛出错误
    if (responseData && typeof responseData === 'object' && responseData.code !== undefined) {
      if (responseData.code !== 200) {
        console.error('上传响应错误:', response.config.url, responseData);
        const error = new Error(responseData.message || '上传失败');
        error.response = response;
        error.code = responseData.code;
        return Promise.reject(error);
      }
    }
    
    console.log('上传响应成功:', response.config.url, responseData);
    return responseData;
  },
  error => {
    console.error('上传响应错误:', error.config?.url, error.message, error.response?.data);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 添加故障转移和CSRF Token处理
api.interceptors.response.use(
  response => {
    // 从响应头获取CSRF Token并保存
    const csrfToken = response.headers['x-csrf-token'];
    if (csrfToken) {
      localStorage.setItem('csrfToken', csrfToken);
    }
    
    // 对于 blob 响应，直接返回 response，不要返回 response.data
    // 因为 axios 已经将 blob 数据放在 response.data 中了
    if (response.config.responseType === 'blob') {
      console.log('Blob响应成功:', response.config.url, '大小:', response.data?.size || 0, 'bytes');
      return response; // 返回完整的 response 对象，包含 data 和 headers
    }
    
    const responseData = response.data;
    
    // 检查响应数据中的code字段，如果不是200，抛出错误
    if (responseData && typeof responseData === 'object' && responseData.code !== undefined) {
      if (responseData.code !== 200) {
        console.error('API响应错误:', response.config.url, responseData);
        const error = new Error(responseData.message || '请求失败');
        error.response = response;
        error.code = responseData.code;
        return Promise.reject(error);
      }
    }
    
    console.log('响应成功:', response.config.url, responseData);
    return responseData;
  },
  error => {
    console.error('响应错误:', error.config.url, error.message);

    // 如果是网络错误或超时，尝试故障转移
    if (!error.response || error.code === 'ECONNABORTED') {
      return handleFailover(error.config);
    }

    if (error.response?.status === 401) {
      // 清除token和用户信息（只清除sessionStorage）
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('user');
      window.location.href = '/';
    }
    return Promise.reject(error);
  }
);

// 故障转移处理
let currentServerIndex = 0;
const handleFailover = async (originalConfig) => {
  // 切换到下一个服务器
  currentServerIndex = (currentServerIndex + 1) % API_BASE_URLS.length;
  currentApiBaseUrl = API_BASE_URLS[currentServerIndex];

  console.log(`🔄🔄 故障转移到服务器: ${currentApiBaseUrl}`);

  try {
    // 创建新的 axios 实例
    const newApiInstance = createApiInstance(currentApiBaseUrl);

    // 复制原始配置
    const newConfig = {
      ...originalConfig,
      baseURL: currentApiBaseUrl
    };

    // 重新发送请求
    const response = await newApiInstance.request(newConfig);
    return response.data;
  } catch (retryError) {
    console.error('故障转移失败:', retryError);
    throw retryError;
  }
};

// 集群健康检查
const checkClusterHealth = async () => {
  const healthChecks = await Promise.allSettled(
    API_BASE_URLS.map(url =>
      axios.get(`${url}/file/health`, { timeout: 5000 })
    )
  );

  const healthStatus = healthChecks.map((result, index) => ({
    url: API_BASE_URLS[index],
    status: result.status === 'fulfilled' ? 'UP' : 'DOWN',
    data: result.status === 'fulfilled' ? result.value.data : null
  }));

  return healthStatus;
};

// API 方法
export const childEnglishApi = {
  // 集群相关
  checkClusterHealth,

  // 获取当前使用的服务器
  getCurrentServer() {
    return currentApiBaseUrl;
  },

  // 切换到指定服务器
  switchServer(index) {
    if (index >= 0 && index < API_BASE_URLS.length) {
      currentServerIndex = index;
      currentApiBaseUrl = API_BASE_URLS[index];
      console.log(`🔀🔀 切换到服务器: ${currentApiBaseUrl}`);
    }
  },

  // 文件上传相关API
  // 普通文件上传
  async uploadFile(file, onProgress = null, fileType = null) {
    const formData = new FormData();
    formData.append('file', file);
    if (fileType) {
      formData.append('fileType', fileType);
    }

    const config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    };

    if (onProgress) {
      config.onUploadProgress = onProgress;
    }

    const response = await uploadApi.post('/file/upload', formData, config);
    return response;
  },

  // 检查分片状态
  async checkChunkStatus(data) {
    const response = await api.get('/file/chunk/status', { params: data });
    return response;
  },

  // 上传分片
  async uploadChunk(chunkData, chunkFile, onProgress = null) {
    const formData = new FormData();
    formData.append('chunk', chunkFile);

    // 添加其他参数
    Object.keys(chunkData).forEach(key => {
      formData.append(key, chunkData[key]);
    });

    const config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    };

    if (onProgress) {
      config.onUploadProgress = onProgress;
    }

    const response = await uploadApi.post('/file/chunk/upload', formData, config);
    return response;
  },

  // 合并分片
  async mergeChunks(data) {
    const response = await api.post('/file/chunk/merge', null, { params: data });
    return response;
  },

  // 清理分片
  async cleanupChunks(fileMd5) {
    const response = await api.delete('/file/chunk/cleanup', {
      params: { fileMd5 }
    });
    return response;
  },

  // 文件下载相关API
  // 获取文件下载信息
  async getDownloadInfo(fileName) {
    const response = await api.get(`/file/download/info/${fileName}`);
    console.log('getDownloadInfo 响应:', response);
    // 确保返回 data 字段
    if (response && response.data) {
      return response.data;
    }
    return response;
  },

  // 下载文件（支持断点续传）
  async downloadFile(fileName, range = null, onProgress = null) {
    const config = {
      responseType: 'blob',
      headers: {}
    };

    if (range) {
      config.headers.Range = range;
    }

    if (onProgress) {
      config.onDownloadProgress = onProgress;
    }

    const response = await api.get(`/file/download/${fileName}`, config);
    return response;
  },

  // 获取文件列表
  async getFileList(params = {}) {
    const response = await api.get('/file/list', { params });
    return response;
  },

  // 获取文件信息
  async getFileInfo(fileName) {
    const response = await api.get(`/file/info/${fileName}`);
    return response;
  },

  // 删除文件
  async deleteFile(fileName) {
    const response = await api.delete(`/file/delete/${fileName}`);
    return response;
  },

  // 原有API保持不变
  async register(userData) {
    const response = await api.post('/api/register', userData);
    return response;
  },

  async registerChild(childData) {
    const response = await api.post('/api/register-child', childData);
    return response;
  },

  async checkUsername(username) {
    const response = await api.get(`/api/check-username?username=${username}`);
    return response;
  },

  async validatePassword(password) {
    const response = await api.post('/api/validate-password', { password });
    return response;
  },

  async validateEmail(email) {
    const response = await api.post('/api/validate-email', { email });
    return response;
  },

  async validatePhone(phone) {
    const response = await api.post('/api/validate-phone', { phone });
    return response;
  },

  async getClasses() {
    const response = await api.get('/api/classes');
    return response;
  },

  async createClass(classData) {
    const response = await api.post('/api/classes', classData);
    return response;
  },

  async updateClass(classId, classData) {
    const response = await api.put(`/api/classes/${classId}`, classData);
    return response;
  },

  async deleteClass(classId) {
    const response = await api.delete(`/api/classes/${classId}`);
    return response;
  },

  async getStudents(classId = null) {
    try {
      const params = classId ? { classId } : {};
      console.log('调用getStudents API, params:', params);
      const response = await api.get('/api/students', { params });
      console.log('getStudents API原始响应:', response);
      return response;
    } catch (error) {
      console.error('getStudents API调用失败:', error);
      throw error;
    }
  },

  async getStudentDetail(studentId) {
    const response = await api.get(`/api/students/${studentId}`);
    return response;
  },

  async updateStudent(studentId, studentData) {
    const response = await api.put(`/api/students/${studentId}`, studentData);
    return response;
  },

  async getAppInfo() {
    const response = await api.get('/');
    return response;
  },

  async login(credentials) {
    const response = await api.post('/login', credentials);
    return response;
  },

  async logout() {
    try {
      const csrfToken = localStorage.getItem('csrfToken');
      console.log('发送登出请求，CSRF Token:', csrfToken ? '已设置' : '未设置');
      
      // 优先使用 fetch with keepalive，因为它支持自定义请求头（包括 CSRF token）
      // sendBeacon 不能设置自定义请求头，可能导致 CSRF 验证失败
      if (fetch && typeof fetch === 'function') {
        try {
          const response = await fetch(`${currentApiBaseUrl}/logout`, {
            method: 'POST',
            credentials: 'include',
            keepalive: true, // 确保在页面卸载时也能完成请求
            headers: {
              'Content-Type': 'application/json',
              'X-CSRF-TOKEN': csrfToken || ''
            },
            body: JSON.stringify({}) // 空的请求体
          });
          console.log('登出请求已发送，状态:', response.status);
        } catch (fetchError) {
          console.warn('fetch with keepalive 失败，尝试使用 sendBeacon:', fetchError);
          // 降级到 sendBeacon
          if (navigator.sendBeacon) {
            const formData = new FormData();
            if (csrfToken) {
              formData.append('csrfToken', csrfToken);
            }
            const sent = navigator.sendBeacon(`${currentApiBaseUrl}/logout`, formData);
            console.log('sendBeacon 发送结果:', sent ? '成功' : '失败');
          }
        }
      } else if (navigator.sendBeacon) {
        // 降级方案：使用 sendBeacon
        const formData = new FormData();
        if (csrfToken) {
          formData.append('csrfToken', csrfToken);
        }
        const sent = navigator.sendBeacon(`${currentApiBaseUrl}/logout`, formData);
        console.log('sendBeacon 发送结果:', sent ? '成功' : '失败');
      }
    } catch (error) {
      console.error('登出请求失败:', error);
      // 即使失败也继续清理本地数据
    }
  },

  // 获取验证码
  async getCaptcha() {
    const response = await api.get('/api/captcha');
    return response;
  },

  // 找回密码相关API
  async sendResetCode(data) {
    const response = await api.post('/api/forgot-password/send-code', data);
    return response;
  },

  async resetPassword(data) {
    const response = await api.post('/api/forgot-password/reset', data);
    return response;
  },

  // 用户管理相关API
  async getAllUsers() {
    const response = await api.get('/admin/users/all');
    return response;
  },

  async addUser(data) {
    const response = await api.post('/admin/user/add', data);
    return response;
  },

  async updateUser(data) {
    const response = await api.post('/admin/user/update', data);
    return response;
  },

  async deleteUser(data) {
    const response = await api.post('/admin/user/delete', data);
    return response;
  },

  async getUserInfo() {
    const response = await api.get('/user/info');
    return response;
  },

  async getUserPermissions(userId = null) {
    try {
      let url = '/user/permissions';
      if (userId) {
        url += `?userId=${userId}`;
      }
      const response = await api.get(url);
      return response;
    } catch (error) {
      console.error('获取用户权限失败:', error);
      return {
        code: 200,
        data: {
          permissions: []
        }
      };
    }
  },

  async getListeningData() {
    const response = await api.get('/learning/listening');
    return response;
  },

  // 绘本阅读相关API
  async getRecommendedBooks() {
    const response = await api.get('/learning/reading/books');
    return response;
  },

  async getBookDetail(bookId) {
    const response = await api.get(`/learning/reading/books/${bookId}`);
    return response;
  },

  async updateReadingProgress(data) {
    const response = await api.post('/learning/reading/progress', data);
    return response;
  },

  async getGameLevels(difficulty = 'easy') {
    const response = await api.get('/learning/game/levels', {
      params: { difficulty }
    });
    return response;
  },

  async getChildLearningProgress() {
    const response = await api.get('/parent/child/learning');
    return response;
  },

  async healthCheck() {
    const response = await api.get('/health');
    return response;
  },

  async clusterHealth() {
    const response = await api.get('/cluster/health');
    return response;
  },

  async sessionTest() {
    const response = await api.get('/cluster/session/test');
    return response;
  },

  async getAdminData() {
    const response = await api.get('/admin/users');
    return response;
  },

  async updateRolePermissions(data) {
    console.log('发送权限更新请求:', JSON.stringify(data, null, 2));
    try {
        const response = await api.post('/admin/role/permissions', data);
        console.log('权限更新响应:', response);
        return response;
    } catch (error) {
        console.error('权限更新请求失败:', error);
        console.error('错误详情:', {
            message: error.message,
            response: error.response?.data,
            status: error.response?.status
        });
        throw error;
    }
  },

  async updateUserRole(data) {
    const response = await api.post('/admin/user/role', data);
    return response;
  },

  async getRolePermissions(roleId) {
    console.log('获取角色权限:', roleId);
    try {
        const response = await api.get(`/admin/role/${roleId}/permissions`);
        console.log('角色权限响应:', response);
        return response;
    } catch (error) {
        console.error('获取角色权限失败:', error);
        return {
            code: 200,
            data: {
                roleId: roleId,
                permissions: []
            }
        };
    }
  },

  async testAdmin() {
    const response = await api.get('/admin/test');
    return response;
  },

  async testAdminPost(data) {
    const response = await api.post('/admin/test-post', data);
    return response;
  },

  async testAllComponents() {
    try {
      const response = await this.healthCheck();
      return response;
    } catch (error) {
      console.error('组件测试失败:', error);
      throw error;
    }
  },

  async testComponent(endpoint) {
    try {
      const response = await api.get(endpoint);
      return response;
    } catch (error) {
      console.error('组件测试失败:', error);
      throw error;
    }
  },

  // 内容审核相关API
  async getPendingReviewItems(params = {}) {
    const response = await api.get('/admin/review/pending', { params });
    return response;
  },

  async approveContent(data) {
    const response = await api.post('/admin/review/approve', data);
    return response;
  },

  async rejectContent(data) {
    const response = await api.post('/admin/review/reject', data);
    return response;
  },

  // 数据监控相关API
  async getMonitorData() {
    const response = await api.get('/admin/monitor/data');
    return response;
  },

  // 获取已审核内容
  async getReviewedContent() {
    const response = await api.get('/admin/review/reviewed');
    return response;
  },

  // 获取在线用户列表
  async getOnlineUsers() {
    const response = await api.get('/admin/online-users');
    return response;
  },

  // 发音评测相关API
  async evaluatePronunciation(text, audioFile) {
    const formData = new FormData();
    formData.append('text', text);
    formData.append('audio', audioFile);

    const response = await uploadApi.post('/speech/evaluate', formData);
    return response;
  },

  // 获取排行榜
  async getLeaderboard(classId = null) {
    try {
      let url = '/learning/leaderboard';
      if (classId) {
        url += `?classId=${classId}`;
      }
      const response = await api.get(url);
      return response;
    } catch (error) {
      console.error('获取排行榜失败:', error);
      // 返回空数据，让前端使用本地数据
      return {
        code: 200,
        data: {
          ranking: []
        }
      };
    }
  }
};

export default api;
